import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_cookie_manager/webview_cookie_manager.dart';
import 'package:url_launcher/url_launcher.dart';

void main() async {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  var htmlstring = '';
  Future<String>? htmlAsset;
  final cookieManager = WebviewCookieManager();
  @override
  void initState() {
    super.initState();
    htmlAsset = _getHtmlAssets('assets/index.html');
  }

  static Future<String> _getHtmlAssets(String assetPath) async {
    final htmlString = await rootBundle.loadString(assetPath);
    final contentBase64 = base64Encode(Utf8Encoder().convert(htmlString));
    return 'data:text/html;base64,$contentBase64';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('title'),
        actions: [
          TextButton(
            onPressed: () async {
              await cookieManager.setCookies([
                Cookie('cookieName2', 'cookieValue3')
                  ..domain = 'www.baidu.com'
                  ..expires = DateTime.now().add(Duration(days: 10))
                  ..httpOnly = false
              ]);
              await launch('https://www.baidu.com');
            },
            child: Text('open in browser'),
          )
        ],
      ),
      body: FutureBuilder<String>(
        future: htmlAsset,
        builder: (contxt, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return WebView(
              initialUrl: 'https://www.baidu.com',
            );
          }
          return Container();
        },
        initialData: 'about:blank',
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          await cookieManager.setCookies([
            Cookie('cookieName', 'cookieValue')
              ..domain = 'www.baidu.com'
              ..expires = DateTime.now().add(Duration(days: 10))
              ..httpOnly = false
          ]);
        },
        child: Text('cookie'),
      ),
    );
  }
}
